//
//  OrderCargoChooseVC.m
//  KuWoCan
//
//  Created by hwd on 17/3/14.
//  Copyright © 2017年 hwd. All rights reserved.
//

#import "OrderCargoChooseVC.h"
#import "DefaultAddressCell.h"
#import "orderTotalCell.h"
#import "CargoCell.h"
#import "RemarkCell.h"
#import "AddressChooseVC.h"
#import "CargoChooseVC.h"
#import "BottomTotalView.h"
#import "NWAddressRequest.h"
#import "AddressModel.h"
#import "NwOrderRequest.h"
#import "OrderManageVC.h"
#import "KwSegViewHelper.h"

#define kCommitOrderPara_Key_Memo         @"orderMemo"

#define kCommitOrderPara_Key_ItemList     @"kwOrderItemList"

#define kCommitOrderPara_Key_TotalBox     @"totalBox"

#define kCommitOrderPara_Key_TotalPrice   @"totalPrice"

#define kCommitOrderPara_Key_TotalWeight  @"totalWeight"

#define kCommitOrderPara_Key_UserName     @"userName"

#define kCommitOrderPara_Key_UserPhone    @"userPhone"

#define kCommitOrderPara_Key_UserAddress  @"userAddress"



@interface OrderCargoChooseVC ()<UITableViewDataSource,UITableViewDelegate>

@property (nonatomic,strong) TPKeyboardAvoidingTableView *tableview;

@property (nonatomic,strong) AddressModel *addressModel;

@property (nonatomic,strong) NSMutableDictionary *paraDic;

@property (nonatomic,strong) NSMutableArray *paraDataArr;

@property (nonatomic,assign) NSInteger totalBox;

@property (nonatomic,assign) CGFloat totalPrice;

@property (nonatomic,strong) BottomTotalView *bottomView;

//因为地址数据模型的冲突.如果更改了地址,就换另一种地址的model  AddressModel
@property (nonatomic,assign) BOOL isNotDetailModel_Address;

//因为商品数据模型的冲突.如果进入商场更改了商品,就换另一种商品的model   ESSInventoryModel
@property (nonatomic,assign) BOOL isNotDetailModel_Cargo;

@property (nonatomic,strong) NSString *memoStr;  //备注

@end

//商品选购
@implementation OrderCargoChooseVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    [self paraDic];
    [self paraDataArr];
    if (_type == VCTypeCommit)
    {
        [self getAddressData];
    }
    else
    {
        //根据传来的参数,得到参数字典
        [self prepareDataForChangeOrder];
        [self setUpUI];
    }
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    KwSegViewHelper *kwHelper = [[KwSegViewHelper alloc] init];
    kwHelper.kwSegIndex = 0;
}

- (NSMutableDictionary *)paraDic
{
    if (!_paraDic)
    {
        _paraDic = [NSMutableDictionary dictionary];
    }
    return _paraDic;
}

- (NSMutableArray *)paraDataArr
{
    if (!_paraDataArr)
    {
        _paraDataArr = [NSMutableArray array];
    }
    return _paraDataArr;
}


- (void)getAddressData
{
    NWAddressRequest *request = [[NWAddressRequest alloc] init];
    [request startRequestGetAllAddressWithUserId:[Singleton shareInstance].userId];
    [request completion:^(id result, NSString *message, id extension, BOOL succ) {
        if (succ)
        {
            NSMutableArray<AddressModel *> *addressArr = [AddressModel arrayOfModelsFromDictionaries:result];

            [addressArr enumerateObjectsUsingBlock:^(AddressModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                if ([obj.isDefault isEqualToString:@"1"]) {
                    _addressModel = obj;
                }
            }];
            if (!_addressModel) {
                _addressModel = addressArr.firstObject;
            }

            [self setUpUI];
        }
    }];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)setUpUI
{
    self.view.backgroundColor = [UIColor whiteColor];
    self.title = @"订单详情";
    //创建列表
    _tableview = [[TPKeyboardAvoidingTableView
                   alloc] initWithFrame:CGRectMake(0, 0, 0, 0) style:UITableViewStylePlain];
    _tableview.backgroundColor = KwBgColor;
    _tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableview.estimatedRowHeight = 40.0;
    _tableview.rowHeight = UITableViewAutomaticDimension;
    _tableview.delegate = self;
    _tableview.dataSource = self;
    [self.view addSubview:_tableview];
    [_tableview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(@0);
        make.left.right.equalTo(@0);
        make.bottom.equalTo(@-55);
    }];

    //创建底部按钮
    __weak typeof(self) weakSelf = self;
    _bottomView = [BottomTotalView new];
    _bottomView.backgroundColor = [UIColor whiteColor];
    _bottomView.oTotalParaLab.text = [NSString stringWithFormat:@"¥%.2f",_totalPrice];
    _bottomView.oNumberLab.text = [NSString stringWithFormat:@"共%ld件商品",(long)_totalBox];
    [self.view addSubview:_bottomView];
    _bottomView.block = ^(){
        [weakSelf confirmCommit];
    };
    [_bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.right.equalTo(@0);
        make.top.equalTo(_tableview.mas_bottom);
    }];
}

//最终的上传参数
- (void)finalParaDic
{
    NSLog(@"_paraDic========%@",_paraDic);
    if (_type == VCTypeCommit)  //提交订单
    {
        [_paraDic setValue:_orderStatus ?: @"1" forKey:@"orderStatus"];
        [_paraDic setValue:_approvalType ?: @"0" forKey:@"approvalType"];
        [_paraDic setValue:[Singleton shareInstance].userId forKey:@"user.id"];

        [_paraDic setValue:_addressModel.name  forKey:kCommitOrderPara_Key_UserName];
        [_paraDic setValue:_addressModel.phone forKey:kCommitOrderPara_Key_UserPhone];
        [_paraDic setValue:_addressModel.address forKey:kCommitOrderPara_Key_UserAddress];
    } else if (_type == VCTypeChange) {
        [_paraDic setValue:_infoModel.id forKey:@"id"];
    }
}

- (void)prepareDataForChangeOrder  //修改订单进入后 显示传来的数据
{
    [_paraDic setValue:_infoModel.userName  forKey:kCommitOrderPara_Key_UserName];
    [_paraDic setValue:_infoModel.userPhone forKey:kCommitOrderPara_Key_UserPhone];
    [_paraDic setValue:_infoModel.userAddress forKey:kCommitOrderPara_Key_UserAddress];
    [_paraDic setValue:[Singleton shareInstance].userId forKey:@"user.id"];
    [_paraDic setValue:_infoModel.totalBox forKey:@"totalBox"];
    [_paraDic setValue:_infoModel.totalPrice forKey:@"totalPrice"];
    [_paraDic setValue:_infoModel.totalWeight forKey:@"totalWeight"];
    [_paraDic setValue:_infoModel.orderMemo forKey:kCommitOrderPara_Key_Memo];

    _totalBox = [_infoModel.totalBox integerValue];
    _totalPrice = [_infoModel.totalPrice floatValue];

    if (_cargoListArr && _cargoListArr.count > 0)
    {
        for (int i = 0; i<_cargoListArr.count; i++)
        {
            OrderDetailListModel *model = _cargoListArr[i];
            [_paraDataArr addObject:@{kOrderItemPara_Key_ProductAttributeId:model.productAttributeId,kOrderItemPara_Key_ProductName:model.productName,kOrderItemPara_Key_Price:model.price,kOrderItemPara_Key_Quantity:model.quantity,kOrderItemPara_Key_Weight:model.weight}];
        }
        NSString *dataStr = [CommonTool beJsonStrWithObj:_paraDataArr];
        [_paraDic setValue:dataStr forKey:kCommitOrderPara_Key_ItemList];
    }
}


//下单
- (void)confirmCommit
{
    [self finalParaDic];
    BOOL allowCommit = YES;

    if (_type == VCTypeCommit)
    {
        if (_paraDic.count == 11)
        {
            for (NSString *str in _paraDic)
            {
                if ([CommonTool checkStringIsEmpty:str])
                {
                    allowCommit = NO;
                }
            }
        }
        else
        {
            allowCommit = NO;
        }

        if (allowCommit == YES)
        {
            NwOrderRequest *request = [[NwOrderRequest alloc] init];
            [request startRequestCommitOrdersWithDic:_paraDic];
            [request completion:^(id result, NSString *message, id extension, BOOL succ) {
                if (succ)
                {
                    [SVProgressHUD showSuccessWithStatus:@"订单提交成功"];
                    [self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:1] animated:YES];
                } else {
                    [SVProgressHUD showErrorWithStatus:message];
                }
            }];
        }
        else
        {
            [SVProgressHUD showErrorWithStatus:@"请完善信息后提交"];
        }

    }
    else
    {
        if (_paraDic.count == 10)
        {
            for (NSString *str in _paraDic)
            {
                if ([CommonTool checkStringIsEmpty:str])
                {
                    allowCommit = NO;
                }
            }
        }
        else
        {
            allowCommit = NO;
        }

        if (allowCommit == YES)
        {
            [self showSelectViewWithTitle:@"是否确认修改" ActionBlock:^{
                NwOrderRequest *request = [[NwOrderRequest alloc] init];
                [request startRequestUpdateOrdersWithDic:_paraDic];
                [request completion:^(id result, NSString *message, id extension, BOOL succ) {
                    if (succ)
                    {
                        [SVProgressHUD showSuccessWithStatus:@"订单提交成功"];
                        [self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:1] animated:YES];
                    } else {
                        [SVProgressHUD showErrorWithStatus:message];
                    }
                }];
            }];
        }
        else
        {
            [SVProgressHUD showErrorWithStatus:@"请完善信息后提交"];
        }
    }
}




//创建第一行酷我商城单元格
- (void)createCellUIWithCell:(UITableViewCell *)cell
{
    UIImageView *img = [UIImageView new];
    img.image = kImg(@"shangchen");
    [cell addSubview:img];
    [img mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(@15);
        make.top.equalTo(@10);
        make.size.mas_equalTo(CGSizeMake(20, 20));
    }];

    UILabel *lab = [UILabel new];
    lab.text = @"酷我商城";
    lab.font = KwFont(14.0);
    [cell addSubview:lab];
    [lab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(img.mas_right).offset(10);
        make.height.equalTo(@14);
        make.top.equalTo(img.mas_top);
    }];

    UIImageView *img2 = [UIImageView new];
    img2.image = kImg(@"next");
    [cell addSubview:img2];
    [img2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(@-15);
        make.size.mas_equalTo(CGSizeMake(12, 15));
        make.top.equalTo(img.mas_top);
    }];

    UIView *lineView = [UIView new];
    lineView.backgroundColor = KwGaryColor;
    [cell addSubview:lineView];
    [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(img.mas_bottom).offset(10);
        make.left.right.equalTo(@0);
        make.height.equalTo(@1.5);
        make.bottom.equalTo(@0);
    }];
}

#pragma mark - PromptView
- (void)showSelectViewWithTitle:(NSString *)title ActionBlock:(void(^)()) block {
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title message:@"" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    UIAlertAction *confirmAction = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        if (block) {
            block();
        }
    }];
    [alertController addAction:confirmAction];
    [alertController addAction:cancelAction];
    [self presentViewController:alertController animated:YES completion:nil];
}


#pragma mark tableViewDelegate,DataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return section == 0 ? 1 : (_cargoListArr &&_cargoListArr.count>0 ? _cargoListArr.count + 3 : 2);
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == _cargoListArr.count+2) {
        return 100*screenW_6;
    }
    return UITableViewAutomaticDimension;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *defaultAddress_ID = @"DefaultAddressCell";
    static NSString *cargoCell_ID = @"CargoCell";
    static NSString *orderTotalCell_ID = @"orderTotalCell";
    static NSString *remarkCell_ID = @"RemarkCell";

    if (indexPath.section == 0)
    {
        DefaultAddressCell *cell;
        cell = [tableView dequeueReusableCellWithIdentifier:defaultAddress_ID];
        if (!cell)
        {
            cell = [[DefaultAddressCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:defaultAddress_ID];
        }
        if (_type == VCTypeChange)
        {
            if (!_isNotDetailModel_Address)
            {
                cell.detailModel = _infoModel;
            }
            else
            {
                if (_addressModel)
                {
                    cell.model = _addressModel;
                }
            }
        }
        else
        {
            if (_addressModel)
            {
                cell.model = _addressModel;
            }
        }
        return cell;
    }
    else
    {
        if (_cargoListArr &&_cargoListArr.count>0)
        {
            if (indexPath.row == 0)
            {
                UITableViewCell *cell;
                //这一行为 酷我商城
                cell = [tableView dequeueReusableCellWithIdentifier:@"tempCell_Id"];
                if (!cell) {
                    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"tempCell_Id"];
                    [self createCellUIWithCell:cell];
                }
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                return cell;
            }
            else if (indexPath.row == _cargoListArr.count+2)
            {
                RemarkCell *cell;
                //这一行为订单备注
                cell = [tableView dequeueReusableCellWithIdentifier:remarkCell_ID];
                if (!cell)
                {
                    cell = [[RemarkCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:remarkCell_ID];
                }
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                cell.remarkTxtF.text = _paraDic[kCommitOrderPara_Key_Memo];
                if (cell.remarkTxtF.text.length > 0) {
                    cell.placeLab.hidden = YES;
                }
                
                cell.block = ^(NSString *txt){
                    if ([txt isEqualToString:@""] || [txt isEmptyString]) {
                        return ;
                    }
                    [_paraDic setValue:txt forKey:kCommitOrderPara_Key_Memo];
                };
                return cell;
            }
            else if(indexPath.row == _cargoListArr.count+1)
            {
                orderTotalCell *cell;
                //这一行为合计
                cell = [tableView dequeueReusableCellWithIdentifier:orderTotalCell_ID];
                if (!cell)
                {
                    cell = [[orderTotalCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:orderTotalCell_ID];
                }
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                cell.oTotalParaLab.text = [NSString stringWithFormat:@"¥%.2f",_totalPrice];
                cell.oNumberLab.text = [NSString stringWithFormat:@"共%ld件商品",(long)_totalBox];
                return cell;
            }
            else
            {
                CargoCell *cell;
                //其余为商品展示
                cell = [tableView dequeueReusableCellWithIdentifier:cargoCell_ID];
                if (!cell)
                {
                    cell = [[CargoCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cargoCell_ID];
                }
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                if (_type == VCTypeChange)
                {
                    if (!_isNotDetailModel_Cargo)
                    {
                        if (_cargoListArr && _cargoListArr.count>0)
                        {
                            OrderDetailListModel *model = _cargoListArr[indexPath.row-1];
                            cell.orderModel = model;
                        }
                    }
                    else
                    {
                        if (_cargoListArr && _cargoListArr.count>0)
                        {
                            ESSInventoryModel *model = _cargoListArr[indexPath.row-1];
                            cell.model = model;
                        }
                    }
                }
                else
                {
                    if (_cargoListArr && _cargoListArr.count>0)
                    {
                        ESSInventoryModel *model = _cargoListArr[indexPath.row-1];
                        cell.model = model;
                    }
                }
                return cell;
            }
        }
        else
        {
            if (indexPath.row == 0)
            {
                UITableViewCell *cell;
                //这一行为 酷我商城
                cell = [tableView dequeueReusableCellWithIdentifier:@"tempCell_Id"];
                if (!cell) {
                    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"tempCell_Id"];
                    [self createCellUIWithCell:cell];
                }
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                return cell;
            }
            else
            {
                UITableViewCell*cell = [tableView dequeueReusableCellWithIdentifier:@"tempCell3"];
                if (!cell) {
                    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"tempCell3"];
                    UIImageView *img = [UIImageView new];
                    img.image = kImg(@"nodata");
                    [cell addSubview:img];
                    __weak UITableViewCell *weakCell  = cell;
                    [img mas_makeConstraints:^(MASConstraintMaker *make) {
                        make.centerX.equalTo(weakCell.mas_centerX);
                        make.top.equalTo(weakCell.mas_top).offset(30);
                        make.bottom.equalTo(weakCell.mas_bottom).offset(-30);
                        make.size.mas_equalTo(CGSizeMake(150, 120));
                    }];
                }
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                return cell;
            }
        }
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0)
    {
        AddressChooseVC *vc = [[AddressChooseVC alloc] init];
        __weak typeof(self) weakSelf = self;
        vc.reloadBlock = ^{
            [weakSelf getAddressData];
        };
        vc.block = ^(AddressModel *model){
            _addressModel = model;
            _isNotDetailModel_Address = YES;
            NSIndexSet *indeSec = [NSIndexSet indexSetWithIndex:0];
            [_tableview reloadSections:indeSec withRowAnimation:UITableViewRowAnimationAutomatic];
            [_paraDic setValue:_addressModel.name forKey:kCommitOrderPara_Key_UserName];
            [_paraDic setValue:_addressModel.phone forKey:kCommitOrderPara_Key_UserPhone];
            [_paraDic setValue:[NSString stringWithFormat:@"%@%@",_addressModel.region,_addressModel.address] forKey:kCommitOrderPara_Key_UserAddress];

        };
        [self.navigationController pushViewController:vc animated:YES];
    }
    else if (indexPath.section == 1 && indexPath.row == 0)
    {

        CargoChooseVC *vc = [[CargoChooseVC alloc] init];
        vc.changeOrderCargos = _cargoListArr;
        vc.isNotDetailModel_Order = _isNotDetailModel_Cargo;
        vc.type = CargoVCTypeOrderManage;
        vc.OtherType = 2;
        vc.block = ^(NSMutableArray *cargoArr){
            _cargoListArr = [NSMutableArray arrayWithArray:cargoArr];
            _isNotDetailModel_Cargo = YES;
            NSInteger aTotalBox = 0;
            CGFloat aTotalPrice = 0;
            CGFloat totalWeight = 0;
            for (int i = 0; i<_cargoListArr.count; i++)
            {
                ESSInventoryModel *model = _cargoListArr[i];
                if (![model.specificationsName isEqual:@"其他"]) {
                    aTotalBox = aTotalBox + [model.totalBox integerValue];
                }
                aTotalPrice = aTotalPrice + [model.price floatValue]*[model.totalBox integerValue];
                totalWeight = totalWeight + [model.weight floatValue]*[model.totalBox floatValue];
            }
            _totalBox = aTotalBox;
            _totalPrice=aTotalPrice;
            _bottomView.oTotalParaLab.text = [NSString stringWithFormat:@"¥%.2f",_totalPrice];
            _bottomView.oNumberLab.text = [NSString stringWithFormat:@"共%ld件商品",(long)_totalBox];

            NSIndexSet *indeSec = [NSIndexSet indexSetWithIndex:1];
            [_tableview reloadSections:indeSec withRowAnimation:UITableViewRowAnimationAutomatic];

            //加参数
            [_paraDataArr removeAllObjects];
            for (int i = 0; i<cargoArr.count; i++)
            {
                ESSInventoryModel *model = cargoArr[i];
                [_paraDataArr addObject:@{kOrderItemPara_Key_ProductAttributeId:model.productAttributeId,kOrderItemPara_Key_ProductName:[NSString stringWithFormat:@"%@,%@,%@",model.productName,model.tasteName,model.specificationsName],kOrderItemPara_Key_Price:model.price,kOrderItemPara_Key_Quantity:model.totalBox,kOrderItemPara_Key_Weight:model.weight}];
            }
            NSString *dataStr = [CommonTool beJsonStrWithObj:_paraDataArr];
            [_paraDic setValue:dataStr forKey:kCommitOrderPara_Key_ItemList];

            [_paraDic setValue:[NSString stringWithFormat:@"%ld",(long)aTotalBox] forKey:@"totalBox"];
            [_paraDic setValue:[NSString stringWithFormat:@"%f",aTotalPrice] forKey:@"totalPrice"];
            [_paraDic setValue:[NSString stringWithFormat:@"%f",totalWeight] forKey:@"totalWeight"];


        };
        [self.navigationController pushViewController:vc animated:YES];
    }
    
}


@end
